package com.ck.controller.basic;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.ck.service.BasicService;

public class LoginController extends AbstractController {
	
	private BasicService basicService;
	  
	public void setBasicService(BasicService basicService) {
		this.basicService = basicService;
	}
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Integer type = Integer.parseInt(request.getParameter("userType"));
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		Map model = new HashMap();
		
		//后台校验
		boolean flag = true;
		if( password == null || "".equals(password.trim()) ){
			model.put("error_user", "请输入密码!");
			flag = false;
		}
		if( username == null || "".equals(username.trim()) ){
			model.put("error_user", "请输入用户名!");
			flag = false;
		}
		
		//校验不通过
        if(!flag){
        	model.put("type", type);
        	model.put("username", username);
        	model.put("password", password);
			return new ModelAndView("login", model);
		}
		
		Boolean isLogin = basicService.login(username, password, type, model, request);		
		if(isLogin){
			switch(type) {
			case 1:
				return new ModelAndView("redirect:student/home.html");
			case 2:
				return new ModelAndView("redirect:teacher/home.html");
			case 3:
				return new ModelAndView("redirect:admin/home.html");
			default:
				return new ModelAndView("redirect:login.html");
			}
		}else{
			model.put("type", type);
        	model.put("username", username);
        	model.put("password", password);
			return new ModelAndView("login", model);
		}
	}

}
